#include "Model.h"

Model::Model(vector<EnginePointer<ModelMesh>>* meshes,
		  vector<EnginePointer<MeshSubset>>* subsets,
		  vector<EnginePointer<ModelVertexBuffer>>* vertexBuffers,
	      vector<EnginePointer<ModelIndexBuffer>>* indexBuffers,
		  vector<EnginePointer<Material>>* materials)
{
	this->meshes = meshes;
	this->subsets = subsets;
	this->vertexBuffers = vertexBuffers;
	this->indexBuffers = indexBuffers;
	this->materials = materials;
}

Model::~Model()
{
	UnloadGraphicsContent();

	delete meshes;
	delete subsets;
	delete vertexBuffers;
	delete indexBuffers;
	delete materials;
}

void Model::UnloadGraphicsContent()
{
	for (vector<EnginePointer<Material>>::iterator it = materials->begin(); it != materials->end(); it++)
	{
		(*it)->UnloadGraphicsContent();
	}
	for (vector<EnginePointer<ModelVertexBuffer>>::iterator it = vertexBuffers->begin(); it != vertexBuffers->end(); it++)
	{
		(*it)->UnloadGraphicsContent();
	}
	for (vector<EnginePointer<ModelIndexBuffer>>::iterator it = indexBuffers->begin(); it != indexBuffers->end(); it++)
	{
		(*it)->UnloadGraphicsContent();
	}
	for (vector<EnginePointer<ModelMesh>>::iterator it = meshes->begin(); it != meshes->end(); it++)
	{
		(*it)->UnloadGraphicsContent();
	}
}

HRESULT Model::LoadGraphicsContent(EnginePointer<ID3D10Device>& pDevice)
{
	HRESULT hr;

	for (vector<EnginePointer<Material>>::iterator it = materials->begin(); it != materials->end(); it++)
	{
		hr = (*it)->LoadGraphicsContent(pDevice);
		if (FAILED(hr)) return hr;
	}

	for (vector<EnginePointer<ModelVertexBuffer>>::iterator it = vertexBuffers->begin(); it != vertexBuffers->end(); it++)
	{
		hr = (*it)->LoadGraphicsContent(pDevice);
		if (FAILED(hr)) return hr;
	}

	for (vector<EnginePointer<ModelIndexBuffer>>::iterator it = indexBuffers->begin(); it != indexBuffers->end(); it++)
	{
		hr = (*it)->LoadGraphicsContent(pDevice);
		if (FAILED(hr)) return hr;
	}
	for (vector<EnginePointer<ModelMesh>>::iterator it = meshes->begin(); it != meshes->end(); it++)
	{
		hr = (*it)->LoadGraphicsContent(pDevice);
		if (FAILED(hr)) return hr;
	}

	return S_OK;
}

vector<EnginePointer<ModelMesh>>::iterator Model::meshesBegin()
{
	return meshes->begin();
}

vector<EnginePointer<ModelMesh>>::iterator Model::meshesEnd()
{
	return meshes->end();
}
